package cdbft

import (
	"blockchain/public/function"
)


func commitDelegate(nodeSeq int){
	var commit commitMessage
	commit.nodeSeq=nodeSeq
	commit.tradeHash=commitDataDelegate(nodeSeq)
	commit.sign=function.SignHash(commit.tradeHash,nodeSeq)
	var flagCommitted =make(chan bool)
	go nodeSendCommitMessageDelegate(nodeSeq,flagCommitted,commit)
	<-flagCommitted
}

func nodeSendCommitMessageDelegate(nodeSeq int,flagCommitted chan bool,commit commitMessage){
	for i:=0;i<groupNum;i++{
		select {
		case chanRecCommit[delegate[i]]<-commit:
			FlagCommitted[nodeSeq][delegate[i]]<-true
			close(FlagCommitted[nodeSeq][delegate[i]])
		default:
			FlagCommitted[nodeSeq][delegate[i]]<-false
			close(FlagCommitted[nodeSeq][delegate[i]])

		}
	}
	flagCommitted<-true
	close(flagCommitted)
}


func commitDataDelegate(nodeSeq int)  [32]byte{
	var prepare [2*groupNum/3+1]prepareMessage
	var counter [groupNum*2/3+1]int
	var sameSeq [groupNum*2/3+1]int
	var hash [32]byte
	for i:=0;i<2*groupNum/3+1;i++{
		sameSeq[i]=-1
	}
	count:=0
	for data:=range chanRecPrepare[nodeSeq]{
		res:=function.VerifySignHash(data.tradesHash,data.sign,data.nodeSeq)
		if res{
			prepare[count]=data
			count++
			if count==2*groupNum/3+1{
				break
			}
		}
	}
	for i:=0;i<groupNum*2/3+1;i++{
		if sameSeq[i]==-1{
			sameSeq[i]=i
			counter[i]=1
			for j:=i+1;j<2*groupNum/3+1;j++{
				if prepare[i].tradesHash==prepare[j].tradesHash{
					counter[i]++
					sameSeq[j]=i
				}
			}
		}
	}

	for i:=0;i<groupNum*2/3+1;i++{
		if counter[i]>groupNum/3{
			hash=prepare[i].tradesHash
		}
	}
	return hash
}
